package org.wlgzs.office_exam_student.service;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Date;

import org.wlgzs.office_exam_student.dao.BaseDao;
import org.wlgzs.office_exam_student.entity.User;


/**
*@author song(mejeesong@qq.com)
*2018年1月25日
*
*/
public class UserService extends BaseDao<User>{
	
	private final String getByAccountSql = "select * from tb_user where role = 'student' and username = ? and end_time > now()";
	
	/**
	*@author song(mejeesong@qq.com)
	*@date 2018年1月25日
	*@param account 用户账户
	*@param secPassword 加密处理后的密码
	*@return 登录成功返回User对象，否则返回null
	*
	*/
	public User login(String account, String secPassword) {
		
		User user = exec(qr -> {
			try {
				return qr.query(getByAccountSql,BEAN_HANDLER,account);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return null;
		});
		logger.debug(String.valueOf(user));
		if(user == null) {
			return null;
		}
		String pw = user.getPassword();
		if(secPassword.equals(pw)) {
			user.setLoginTime(new Timestamp(new Date().getTime()));

			updateUser(user);
			return user;
		}
		return null;
	}
	public List<User> getAll(){
		return exec(qr -> {
			String sql = "select * from tb_user";
			try {
				return qr.query(sql, BEAN_LIST_HANDLER);
				//or return qr.query(sql, new BeanListHandler<>(User.class,new HumpRowProcessor(User.class)));
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return null;
		});

	}

	/*
      修改个人资料
      @auther  孤城落寞博客
	 */

	public Object updateUser(User user) {
		String updateSql = "update tb_user set login_time = ? , password = ? , name = ?, phone = ? where  id = ?";

		return  exec( qr -> {
			try {
				return qr.update(updateSql,user.getLoginTime(),user.getPassword(),user.getName(),user.getPhone(),user.getId());

			} catch (SQLException e) {
				e.printStackTrace();

			}
           return  null;
		});
	}

}
